from tortoise.models import Model
from tortoise import fields
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
import os

# Tortoise ORM 连接池配置
TORTOISE_ORM = {
    "connections": {
        "default": {
            "engine": "tortoise.backends.mysql",
            "credentials": {
                "host": os.getenv("DB_HOST", "192.168.25.202"),
                "port": int(os.getenv("DB_PORT", 3306)),
                "user": os.getenv("DB_USER", "root"),
                "password": os.getenv("DB_PASSWORD", "free2walk"),
                "database": os.getenv("DB_NAME", "fastapi_demo"),
                "minsize": int(os.getenv("DB_POOL_MINSIZE", 1)),
                "maxsize": int(os.getenv("DB_POOL_MAXSIZE", 5)),
                "charset": "utf8mb4",
            }
        }
    },
    "apps": {
        "models": {
            "models": ["app.models", "aerich.models"],
            "default_connection": "default",
        }
    },
    "use_tz": False,
    "timezone": "Asia/Shanghai"
}
async def init_db():
    """
    初始化 Tortoise ORM 数据库连接
    """
    return await Tortoise.init(config=TORTOISE_ORM)
    # await Tortoise.generate_schemas()


class BaseModel(Model):
    """
    BaseModel
    """
    id = fields.IntField(pk=True, description="主键ID")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")
    updated_at = fields.DatetimeField(auto_now=True, description="更新时间")

    class Meta:
        abstract = True

